import { NextRequest } from 'next/server';
import { ResponseUtil } from '@/utils/response';
import { WithdrawService } from '@/services/withdrawService';
import { verifyAuth } from '@/utils/auth';
import prisma from '@/lib/prisma';

export async function POST(request: NextRequest) {
  try {
    // 验证用户登录
    const authResult = await verifyAuth(request);
    if (!authResult?.user?.id) {
      return ResponseUtil.unauthorized('未登录');
    }

    let { amount, accountType, accountInfo } = await request.json();
    amount=Number(amount)

  

    // 验证参数
    if (!amount || !accountType || !accountInfo) {
      return ResponseUtil.badRequest('参数不完整');
    }

    if (amount <= 0) {
      return ResponseUtil.badRequest('提现金额必须大于0');
    }

    // 检查金额是否为整数
    if (!Number.isInteger(amount)) {
      return ResponseUtil.badRequest('提现金额必须是整数');
    }

    // 检查金额是否超过10万
    if (amount > 100000) {
      return ResponseUtil.badRequest('提现金额不能超过10万积分');
    }
    const money =amount/10;
    // 检查用户是否有足够的积分
    const user = await prisma.user.findUnique({
      where: { id: authResult.user.id }
    });

    if (!user || user.withDrawPoints < amount) {
      return ResponseUtil.badRequest('可提现积分不足');
    }

    // 计算手续费（10%）
    const fee = amount * 0.1;
    const actualAmount = amount - fee;

    // 生成提现单号
    const withdrawNo = `WD${authResult.user.id}-${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`;

    // 创建用户提现记录
    const userWithdrawRecord = await prisma.userWithdrawRecord.create({
      data: {
        userId: authResult.user.id,
        withdrawNo,
        amount:money,
        actualAmount:money,
        fee,
        accountType,
        accountInfo,
        status: 'PENDING',
        remark: '用户直接提现'
      }
    });

    // 检查记录是否插入成功
    if (!userWithdrawRecord || !userWithdrawRecord.id) {
      return ResponseUtil.serverError('提现记录创建失败');
    }

    console.log('提现记录创建成功:', {
      id: userWithdrawRecord.id,
      withdrawNo: userWithdrawRecord.withdrawNo,
      amount: userWithdrawRecord.amount,
      userId: userWithdrawRecord.userId
    });

    // 扣除用户积分
    await prisma.user.update({
      where: { id: authResult.user.id },
      data: {
        withDrawPoints: {
          decrement: amount
        }
      }
    });

    // 调用支付宝提现服务
    const withdrawResult = await WithdrawService.processAlipayWithdraw({
      amount:money,
      accountType,
      accountInfo,
      userId: authResult.user.id,
      withdrawNo:withdrawNo
    });

    // 更新提现记录状态
    await prisma.userWithdrawRecord.update({
      where: { id: userWithdrawRecord.id },
      data: {
        status: 'PROCESSING'
      }
    });

    return ResponseUtil.success({
      message: '提现申请提交成功',
      data: {
        withdrawId: userWithdrawRecord.id,
        withdrawNo: userWithdrawRecord.withdrawNo,
        amount: userWithdrawRecord.amount,
        actualAmount: userWithdrawRecord.actualAmount,
        fee: userWithdrawRecord.fee,
        status: userWithdrawRecord.status
      }
    });

  } catch (error) {
    console.error('提现处理失败:', error);
    return ResponseUtil.serverError('提现处理失败: ' + (error as Error).message);
  }
}

// 查询提现状态
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const withdrawId = searchParams.get('withdrawId');
    const withdrawNo = searchParams.get('withdrawNo');

    if (!withdrawId && !withdrawNo) {
      return ResponseUtil.error('缺少提现ID或提现单号');
    }

    let withdrawRecord;
    
    if (withdrawId) {
      withdrawRecord = await prisma.userWithdrawRecord.findUnique({
        where: { id: parseInt(withdrawId) }
      });
    } else if (withdrawNo) {
      withdrawRecord = await prisma.userWithdrawRecord.findUnique({
        where: { withdrawNo }
      });
    }

    if (!withdrawRecord) {
      return ResponseUtil.error('提现记录不存在');
    }

    return ResponseUtil.success(withdrawRecord);

  } catch (error) {
    console.error('查询提现状态失败:', error);
    return ResponseUtil.error('查询提现状态失败');
  }
} 